package com.xiyoo.cw.utils;

import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

/**
 * 安全服务工具类
 *
 * @author ruoyi
 */
@Slf4j
@Component
public class SecurityUtils {

    public static String header;

    public static String tokenStartWith;

    @Value("${token.header}")
    public void setHeader(String header) {
        SecurityUtils.header = header;
    }

    @Value("${token.tokenStartWith}")
    public void setTokenStartWith(String header) {
        SecurityUtils.tokenStartWith = header;
    }



    /**
     * 获取用户ID
     *
     * @return 系统用户ID
     */
    public static String getUserEmail() {
        return getUserEmail(getToken());
    }

    /**
     * 获取用户Email
     *
     * @return Email
     */
    private static String getUserEmail(String token) {
        JWT jwt = JWTUtil.parseToken(token);
        return String.valueOf(jwt.getPayload("email"));
    }


    /**
     * 获取Token
     *
     * @return /
     */
    public static String getToken() {
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder
                .getRequestAttributes())).getRequest();
        String bearerToken = request.getHeader(header);
        if (bearerToken != null && bearerToken.startsWith(tokenStartWith)) {
            // 去掉令牌前缀
            return bearerToken.replace(tokenStartWith, "");
        } else {
            log.debug("非法Token：{}", bearerToken);
        }
        return null;
    }


    /**
     * 获取Authentication
     */
    public static Authentication getAuthentication() {
        return SecurityContextHolder.getContext().getAuthentication();
    }

}
